<template>
  <div class="app-container">
    <div v-if="!open">
<!--      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">-->
<!--        <el-form-item label="商家名称" prop="shopName">-->
<!--          <el-input v-model="queryParams.shopName" placeholder="请输入商家地址" clearable size="mini"-->
<!--                    @keyup.enter.native="handleQuery"/>-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>-->
<!--          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>-->
<!--        </el-form-item>-->
<!--      </el-form>-->

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                     v-hasPermi="['module:mer:add']">新增</el-button>
        </el-col>
<!--        <el-col :span="1.5">-->
<!--          <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"-->
<!--                     v-hasPermi="['module:mer:remove']">删除</el-button>-->
<!--        </el-col>-->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table v-loading="loading" :data="merList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商家ID" align="center" prop="id" width="75"/>
<!--        <el-table-column label="商家名称" align="center" prop="shopName" width="180"/>-->
<!--        <el-table-column label="商铺编号" align="center" prop="shopNo" width="140"/>-->
<!--        <el-table-column label="商家LOGO" align="center" width="120">-->
<!--          <template slot-scope="scope">-->
<!--            <a :href="scope.row.shopLogoPath" target="_blank" v-if="scope.row.shopLogoPath!==''">-->
<!--              <img :src="scope.row.shopLogoPath" title="点击打开" style="width: 100px;height: 60px;">-->
<!--            </a>-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="二维码下载" align="center" >
          <template slot-scope="scope">
            <el-popover placement="right" width="400" trigger="hover">
              <el-image style="width: 380px; height: 380px" :src="scope.row.qrCode"  fit="fill" />
              <i class="el-icon-picture" slot="reference"/>
            </el-popover>
            <el-button size="mini" type="text" icon="el-icon-download"
                       @click="downloadImg(scope.row)">{{scope.row.shopName }}</el-button>
          </template>
        </el-table-column>
        <el-table-column label="商品数" align="center" prop="productCount" >
          <template slot-scope="scope">
            <el-button size="mini" type="text">
              <router-link :to="'/mer/service?merId=' + scope.row.id" class="link-type">
                {{'共' + scope.row.productCount +'个'}}
              </router-link>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="负责人" align="center" prop="leaderName"/>
        <el-table-column label="服务电话" align="center" prop="telphone"/>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <div>
              <el-tag v-if="scope.row.state === 0" style="cursor: pointer" :type="''">正常</el-tag>
              <el-tag v-else style="cursor: pointer" :type=" 'info' ">停用</el-tag>
            </div>
          </template>
        </el-table-column>
<!--        <el-table-column label="关注公众号人数" align="center" prop="userMpCount" width="140"/>-->
        <el-table-column label="操作" align="center" width="300px" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-user-solid">
              <router-link :to="'/property/mer/estate/setting?merId=' + scope.row.id+'&estateId=' +scope.row.estateId " class="link-type">
                服务配置
              </router-link>
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-user-solid">
              <router-link :to="'/mer/user?merId=' + scope.row.id + '&from=mer'" class="link-type">
                商家管理员
              </router-link>
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row,false)"
                       v-hasPermi="['module:mer:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['module:mer:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0"
                  :total="total"
                  :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"
                  @pagination="getList" />

    </div>

    <div v-if="open">
      <!-- 添加或修改服务商家对话框 -->
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="13">
            <el-col :span="24">
              <el-form-item label="商家名称" prop="shopName" >
                <el-input v-model="form.shopName" placeholder="请输入商家地址" size="mini" style="width:95%;"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="省市区" prop="provinceArray">
                <AreaOptions ref="AreaOptions" v-if="open" :isHasDis="1"
                             :value="form.provinceArray"
                             @change="handleChangeProvince"
                             @expand-change="handleExpandChange"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务星级" prop="serviceStar">
                <el-input v-model="form.serviceStar" type="number" placeholder="请输入添加时间" style="width:90%;" size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="联系人" prop="leaderName" >
                <el-input v-model="form.leaderName" placeholder="请输入联系人" style="width:90%;" size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="服务电话" prop="telphone">
                <el-input v-model="form.telphone" placeholder="请输入服务电话" style="width:90%;" size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="经纬度" prop="longitude">
                <el-input v-model="form.longitude" placeholder="请输入经度" style="width:47%" size="mini"/>
                <el-input v-model="form.latitude" placeholder="请输入纬度" style="width:47%" size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="状态" prop="state">
                <el-radio-group v-model="form.state" size="mini">
                  <el-radio :value="0" :label="0">正常</el-radio>
                  <el-radio :value="1" :label="1">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="商家地址" prop="address">
                <el-input v-model="form.address" placeholder="请输入商家地址"  style="width:95%;" size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="服务关键字" prop="keyWord" >
                <el-input v-model="form.keyWord" placeholder="请输入服务关键字" style="width:95%;" size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商家LOGO" prop="shopLogo" style="width:95%;">
                <single-pic v-model="form.shopLogoPath" type="image" @handleChecked="chooseImg" :uploadType="8"
                            :num="1" :width="80" :height="80" />
              </el-form-item>
            </el-col>
          </el-col>
          <el-col :span="11">

            <div style="width:100%;height:400px;">
              <TianDiTu :zoom="12" :label-title="form.shopName"
                        :default-lat="parseFloat(form.latitude)" :default-lng="parseFloat(form.longitude)"
                        @pickLngLat="pickLngLat"></TianDiTu>
            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col style="text-align: center;" :span="12">
            <el-button :loading="buttonLoading" size="mini" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel" size="mini">取 消</el-button>
          </el-col>
        </el-row>

      </el-form>
    </div>
  </div>
</template>

<script>
  import { listMer, getMer, delMer, addMer, updateMer,resetQrCode } from "@/api/module/mer/mer";
  import { listType, } from "@/api/module/product/type";
  import singlePic from '@/components/SingleMaterial'

  export default {
    name: "Mer",
    components: {
      singlePic,
      AreaOptions:() => import('@/components/AreaOptions'),
    },
    data() {
      return {
        activeName:'0',
        map:null,
        marker:null,
        tipinput:'',
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        dateRange:[],
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        //子分类
        productTypeChildOptions:[],
        // 总条数
        total: 0,
        // 服务商家表格数据
        merList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        phone:undefined,
        subTypeLabel:'分成比例',
        subTypeUnit:'%',
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          shopType:2,
          estateId:undefined,
        },
        // 查询参数
        queryParamsPty: {
          pageNum: 1,
          pageSize: 100,
          parentId:2,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          shopName: [
            { required: true, message: "用户名称不能为空", trigger: "blur" }
          ],
          address: [
            { required: true, message: "请输入商家地址", trigger: "blur" }
          ],
          leaderName: [
            { required: true, message: "请输入商家联系人", trigger: "blur" }
          ],
          telphone: [
            { required: true, message: "请输入商家电话", trigger: "blur" }
          ],
          // cateChildId:[
          //   { required: true, message: "请选择商家服务类型", trigger: "blur" }
          // ],
          checkState: [
            { required: true, message: "请选择审核状态", trigger: "blur" }
          ],
          checkResult: [
            { required: true, message: "请输入审核结果", trigger: "blur" }
          ],
          // subType: [
          //   { required: true, message: "请选择分成方式", trigger: "blur" }
          // ],
          // subRate: [
          //   { required: true, message: "请输入分成比例", trigger: "blur" }
          // ],
          // subCouponRate: [
          //   { required: true, message: "请输入折扣券分成比例", trigger: "blur" }
          // ],
        },
        isCheck:false,
        user_type:0
      };
    },
    created() {
      this.queryParams.estateId = this.$route.query.estateId ? this.$route.query.estateId : undefined;
      this.getList();
      this.getProductTypeChildList();
    },
    methods: {
      refresh(){
        this.$router.go(0);
      },
      handleClick(val){
        console.log('handleClick',val.name);
        this.activeName = val.name;
        this.queryParams.checkState = parseInt(val.name);
        this.getList();
      },
      /** 查询服务商家列表 */
      getList() {
        this.loading = true;
        listMer(this.queryParams).then(response => {
          this.merList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.user_type = response.otherData.user_type;
        });
      },
      pickLngLat(e){
        console.log('getLngLat e === ', e)
        this.form.longitude = e.lng.toFixed(6);
        this.form.latitude = e.lat.toFixed(6);
      },
      handleChangeProvince(e){
        console.log('handleChangeProvince',e);
        this.form.provinceArray = e;
      },
      // TODO：各父级选项值组成的数组
      handleExpandChange(e){
        console.log(e);
      },
      getProductTypeChildList(){
        listType(this.queryParamsPty).then(response => {
          this.productTypeChildOptions = response.rows;
        });
      },
      changeSubType(val){
        console.log('changeSubType',val);
        if(val === 0){  //按照固定金额
          this.subTypeLabel = "分佣金额";
          this.subTypeUnit = "元";
        }else{ //按照售价比例
          this.subTypeLabel = "分成比例";
          this.subTypeUnit = "%";
        }
      },
      chooseImg(data){
        console.log("chooseImg",data);
        if(data.length > 0) {
          console.log("imgPath",data[0].imgUrl);
          console.log("url",data[0].url);
          this.form.shopLogoPath = data[0].imgUrl;
          this.form.shopLogo = data[0].url;
        }
      },
      downloadImg(row){
        window.location.href = process.env.VUE_APP_BASE_API + "/common/download/mer/" + row.id;
      },
      resetQrCode(row){
        var data = {
          id: row.id
        };
        resetQrCode(data).then(response => {
          if(response.code === 200){
            this.msgSuccess("生成成功");
            this.getList();
          }else{
            this.msgError("生成失败");
          }
        });
      },
      handleUploadSuccess0(data){
        console.log("handleUploadSuccess0 身份证正面",data);

        var imgUrl = data.imgUrl[0].name;
        var imgPath = data.imgUrl[0].url;

        this.form.idCardImgBefore = imgUrl;
        this.form.idCardImgBeforePath = imgPath;
      },
      handleUploadSuccess1(data){
        console.log("handleUploadSuccess1 身份证反面",data);
        var imgUrl = data.imgUrl[0].name;
        var imgPath = data.imgUrl[0].url;

        this.form.idCardImgAfter = imgUrl;
        this.form.idCardImgAfterPath = imgPath;
      },
      handleUploadSuccess2(data){
        console.log("handleUploadSuccess2 身份证合同协议",data);
        var imgUrl = data.imgUrl[0].name;
        var imgPath = data.imgUrl[0].url;

        var imgs = "";
        for (var index in data.imgUrl){
          imgs += data.imgUrl[index].name + ",";
        }
        if(imgs!=''){
          imgs = imgs.substring(0,imgs.length - 1);
        }
        this.form.heTongPic = imgs;
      },
      handleUploadSuccess3(data){
        console.log("handleUploadSuccess1 营业执照",data);
        var imgUrl = data.imgUrl[0].name;
        var imgPath = data.imgUrl[0].url;

        this.form.codeImg = imgUrl;
        this.form.codeImgPath = imgPath;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          userId: undefined,
          estateId:this.queryParams.estateId,
          address: undefined,
          shopName: undefined,
          cateChildId:undefined,
          shopNo: undefined,
          shopLogo: undefined,
          shopLogoPath: undefined,
          provId:undefined,
          cityId:undefined,
          districtId:undefined,
          provName:undefined,
          cityName:undefined,
          districtName:undefined,
          telphone: undefined,
          shopType:2,
          email: undefined,
          longitude: undefined,
          latitude: undefined,
          leaderName:undefined,
          state: undefined,
          isPlatform:1,
          // proCity: undefined,
          createTime: undefined,
          serviceStar: undefined,
          keyWord: undefined,
          maxOrderCount: undefined,
          codeImg:undefined,
          creditCode:undefined,
          idCardImgBefore:undefined,
          idCardImgAfter:undefined,
          idCardImgBeforePath:undefined,
          idCardImgAfterPath:undefined,
          checkState:undefined,
          checkResult:undefined,
          codeImgPath:undefined,
          idCardImgs:undefined,
          isCheck:1,
          subType:1,
          subRate:0.6,
          subCouponRate:undefined,
          heTongPic:undefined,
          heTongPics:undefined,
          signImg:undefined,
          signImgPath:undefined,
          cateChildIds:[],
          subFirstPayRate:undefined,
          provinceArray:[],
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        console.log('dateRange',this.dateRange);
        if(this.dateRange !=undefined && this.dateRange.length === 2){
          this.queryParams.beginDate = this.dateRange[0];
          this.queryParams.endDate = this.dateRange[1];
        }
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length!==1;
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        var that = this;
        this.reset();
        this.isCheck = true;
        this.open = true;
        this.title = "添加服务商家";
      },
      /** 修改按钮操作 */
      handleUpdate(row,isCheck) {
        this.isCheck = isCheck;
        var that = this;
        this.loading = true;
        this.reset();
        const id = row.id || this.ids;
        getMer(id).then(response => {
          console.log('getMer response.data',response.data);
          this.loading = false;
          this.form = response.data;
          this.form.isCheck = isCheck ? 1 :0;
          this.open = true;
          this.title = "修改服务商家";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            if (this.form.id != null) {
              updateMer(this.form).then(response => {
                console.log(this.form.cateChildId)
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addMer(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除服务商家编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          return delMer(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
      },
    }
  };
</script>

<style lang="scss" scoped>
  .mapSelect {
    position: absolute;
    top: 5px;
    right: 1px;
    background: #fff none repeat scroll 0 0;
    border: 1px solid #ccc;
    margin: 10px auto;
    padding:6px;
    font-family: "Microsoft Yahei", "微软雅黑", "Pinghei";
    font-size: 14px;
  }
</style>

<style lang="scss" >
  .amap-sug-result{
    z-index: 99999!important;
  }
</style>
